package org.andy.shop.dao.Impl;

import org.andy.shop.dao.UserInfoDao;
import org.andy.shop.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: Chen
 * @Date: 2016/4/16 14:34
 * @Email: wirechen@gmail.com
 * @Description:
 */
@Repository("userInfoDao")
public class UserInfoDaoImpl implements UserInfoDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public UserInfo getById(Integer id) {

        String sql = "SELECT * FROM user_info WHERE id = ?";

        UserInfo userInfo = jdbcTemplate.queryForObject(sql, new UserInfo(),
                new Object[] { id });

        return userInfo;
    }

    public List<UserInfo> findAll() {
        String sql = "SELECT * FROM user_info";
        List<UserInfo> userInfos = jdbcTemplate.query(sql, new UserInfo());
        return userInfos;
    }

    public Integer save(UserInfo entity) {

        String sql = "INSERT INTO user_info(uname, unumber, uregister_time) VALUES(:uname, :unumber, :uregister_time)";
        MapSqlParameterSource paramSource = new MapSqlParameterSource();
        paramSource.addValue("uname", entity.getUname());
        paramSource.addValue("unumber", entity.getUnumber());
        paramSource.addValue("uregister_time", entity.getuRegisterTime());
        int result = namedParameterJdbcTemplate.update(sql, paramSource);

        return result;
    }

    public void update(UserInfo entity) {

        String sql = "UPDATE user_info SET uname=?,unumber=?,uregister_time=? WHERE id =?";
        Object obj[] = {entity.getUname(),entity.getUnumber(),entity.getuRegisterTime(),entity.getId()};
        int temp = jdbcTemplate.update(sql,obj);
        if(temp>0){
            System.out.println("更新成功！");
        }else{
            System.out.println("更新失败！");
        }
    }

    public void delete(Integer id) {
        String sql = "DELETE FROM user_info WHERE id = "+id;
        int result = jdbcTemplate.update(sql);
        if(result>0){
            System.out.println("删除成功！");
        }else{
            System.out.println("删除失败！");
        }
    }

}
